function countRoom(formdata) {
  console.log(formdata);
  RoomModel.find({
    exam_id : formdata.$loki
  },(err,doc)=>{
    ExamModel.findAndUpdate({$loki:formdata.$loki},{room_count:doc.length});
  });
}
function countUser(formdata) {
  ExamModel.findAndUpdate({$loki:formdata.$loki},{user_count:formdata.length});
}
function countQuestion(formdata) {
  ExamModel.findAndUpdate({$loki:formdata.$loki},{question_count:formdata.length});
}

/**
 * 获取考试列表
 * @returns {function()}
 */
const getExamList = (formdata = {}) => {
  return (dispatch) => {
    ExamModel.find({},(err,doc)=>{
      if(!err){
        return Promise.resolve(dispatch({
          type: 'exam_list',
          examlist : doc
        }))
      }else{
        return Promise.reject('系统错误');
      }
    })
  }
}

/**
 * 获取考试详情
 * @param formdata
 * @returns {function()}
 */
const getExamDetail = (formdata) => {
  // console.log(formdata);
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      ExamModel.findOne({$loki:parseInt(formdata.$loki)},(err,doc)=>{
        // console.log(doc);
        if(!err){
          resolve(dispatch({
            type : 'exam_detail',
            info : doc
          }));
        }else{
          reject('系统错误');
        }
      });
    });
  }
}

/**
 * 添加考试
 * @param formdata
 * @returns {function()}
 */
const postAddExam = (formdata) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      ExamModel.insert(formdata,(err,doc)=>{
        console.log(doc);
        if(!err){
          resolve(dispatch({
            type: 'exam_add',
            info : doc
          }))
        }else{
          reject('系统错误');
        }
      });

    });
  }
}

/**
 * 编辑考试
 * @param formdata
 * @returns {function()}
 */
const postEditExam = (formdata) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      ExamModel.findAndUpdate({$loki:parseInt(formdata.$loki)},formdata,(err,doc)=>{
        if(!err){
          resolve(dispatch({
            type : 'exam_edit',
            info : doc
          }));
        }else{
          reject('系统错误');
        }
      });
    });
  }
}

/**
 * 删除考试
 * @param formdata
 * @returns {function()}
 */
const postDeleteExam = (formdata) => {
  return (dispatch) => {

    return new Promise(function(resolve, reject){
      var doc = ExamModel.chain().find({$loki:formdata.$loki}).data();
      if(doc[0].status === 'end' || doc[0].status === 'exam'){
        reject('考试已经生成,无法删除');
        return;
      };
      ExamModel.findAndRemove({$loki:formdata.$loki},(err,doc)=>{
        RoomModel.findAndRemove({exam_id:formdata.$loki});
        const questionPath = 'dba/questions/question_'+formdata.$loki+'.json';
        lokiApi(questionPath,function (collection) {
          collection.clear();
        });
        const userPath = 'dba/users/user_'+formdata.$loki+'.json';
        lokiApi(userPath,function (collection) {
          collection.clear();
        });

        if(!err){
          resolve(dispatch({
            type : 'exam_delete',
            index : formdata.index
          }));
        }else{
          reject('系统错误');
        }
      });
    });

  }
}

/**
 * 获取考场列表
 * @returns {function()}
 */
const getRoomList = (formdata = {}) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      const doc = RoomModel.chain().find(formdata).simplesort('$loki',false).data();
      resolve(dispatch({
        type: 'room_list',
        info : doc
      }))
    });
  }
}

/**
 * 添加考场
 * @param formdata
 * @returns {function()}
 */
const postAddRoom = (formdata) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      RoomModel.insert(formdata,(err,doc)=>{
        if(!err){
          resolve(dispatch({
            type: 'room_add',
            info : doc
          }));
          countRoom({
            $loki : formdata.exam_id
          });
        }else{
          reject('系统错误');
        }
      });

    });
  }
}

/**
 * 编辑考场
 * @param formdata
 * @returns {function()}
 */
const postEditRoom = (formdata) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      RoomModel.findAndUpdate({$loki:formdata.$loki},formdata,(err,doc)=>{
        if(!err){
          resolve(dispatch({
            type : 'room_edit',
            index : formdata.index,
            info : doc
          }));
        }else{
          reject('系统错误');
        }
      });
    });
  }
}

/**
 * 删除考场
 * @param formdata
 * @returns {function()}
 */
const postDeleteRoom = (formdata) => {
  return (dispatch) => {

    return new Promise(function(resolve, reject){
      RoomModel.findAndRemove({$loki:formdata.$loki},(err,doc)=>{

        if(!err){
          resolve(dispatch({
            type : 'room_delete',
            index : formdata.index
          }));
          countRoom({
            $loki : formdata.exam_id
          });
        }else{
          reject('系统错误');
        }
      });
    });

  }
}


/**
 * 获取题库列表
 * @returns {function()}
 */
const getQuestionList = (formdata = {}) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      lokiApi(formdata.path,function (collection) {
        
        var query = {};
        if(formdata.eq_type && formdata.eq_type.length > 0){
          query['eq_type'] = {'$in':formdata.eq_type};
        };

        if(formdata.questions && formdata.questions.length > 0){
          query['$loki'] = {'$in':formdata.questions};
        };

        if(formdata.course_id){
          query['course_id'] = formdata.course_id;
        }

        if(formdata.questions && formdata.questions.length > 0 && formdata.eq_type && formdata.eq_type.length > 0){
          query = {};
          query['$and'] = [
            {
              'eq_type' : {'$in':formdata.eq_type}
            },
            {
              '$loki' : {'$in':formdata.questions}
            }
          ];
        }

        if(formdata.eq_type && formdata.eq_type.length > 0 && formdata.course_id){
          query = {};
          query['$and'] = [
            {
              'eq_type' : {'$in':formdata.eq_type}
            },
            {
              'course_id' : formdata.course_id
            }
          ];
        }

        console.log(query);

        var doc = collection.chain().find(query).simplesort('$loki',false).data();
        // console.log(doc);

        if(doc){
          resolve(dispatch({
            type : 'question_list',
            info : doc
          }));
        }
      });
    });
  }
}

/**
 * 上传题库,处理json格式
 * @param formdata
 * @returns {function()}
 */
// const postQuestionUploadOld = (formdata) => {
//   return (dispatch) => {
//     return new Promise(function(resolve, reject){
//
//
//       ExamModel.findOne({$loki:parseInt(formdata.$loki)},(err,doc)=>{
//         var questions = [], no = 0, data = {};
//         var filename = formdata.filePath.split(/(\\|\/)/g).pop().replace('.json','');
//         if(doc.exam_questions && doc.exam_questions.length > 0){
//           questions = doc.exam_questions;
//           no = doc.exam_questions_index;
//         };
//         var id = 'q_'+no;
//         data = {
//           id : id,
//           name : filename
//         };
//
//         var tfng_list = [], single_list = [], multiple_list = [];
//         jsonfile.readFile(formdata.filePath, function(err, jsonArray) {
//           const questionPath = 'dba/questions/question_'+formdata.$loki+'.json';
//           if(Object.prototype.toString.call(jsonArray) === "[object Array]"){
//             lokiApi(questionPath,function (collection) {
//
//               jsonArray.forEach(function (value) {
//                 value['course_id'] = id;
//                 var res = collection.insert(value);
//                 if(value.eq_type == 'tfng'){
//                   tfng_list.push(res.$loki);
//                 }else if(value.eq_type == 'single'){
//                   single_list.push(res.$loki);
//                 }else if(value.eq_type == 'multiple'){
//                   multiple_list.push(res.$loki);
//                 };
//
//               });
//               data['tfng_list'] = tfng_list;
//               data['single_list'] = single_list;
//               data['multiple_list'] = multiple_list;
//
//               questions.push(data);
//
//               ExamModel.findAndUpdate({$loki:formdata.$loki},{
//                 exam_questions_index : no + 1,
//                 exam_questions:questions
//               });
//
//               resolve(dispatch({
//                 type : 'question_items',
//                 info : questions
//               }));
//             });
//           }else{
//             reject('文件格式错误');
//           }
//         });
//
//       });
//     });
//
//   }
// }

/**
 * 更改试题数量
 */
const changeQuestionNumber = (formdata = {}) => {

  return (dispatch) => {
    return new Promise(function(resolve, reject){

      ExamModel.findOne({$loki:parseInt(formdata.$loki)},(err,doc)=>{
        var questions = doc.exam_questions;
        questions.forEach((item,key)=>{
          if(item.id == formdata.id){
            questions[key][formdata.type] = formdata.num;
          }
        });
        ExamModel.findAndUpdate({$loki:formdata.$loki},{
          exam_questions:questions
        });

        resolve(dispatch({
          type : 'questions',
          info : questions
        }));

      });

    });
  }
}

/**
 * 删除question
 */
const deleteQuestion = (formdata = {}) => {

  return (dispatch) => {
    return new Promise(function(resolve, reject){

      ExamModel.findOne({$loki:parseInt(formdata.$loki)},(err,doc)=>{
        var questions = doc.exam_questions;
        questions.forEach((item,key)=>{
          if(item.id == formdata.id){
            questions.splice(key,1);
          }
        });

        const questionPath = 'dba/questions/question_'+formdata.$loki+'.json';
        lokiApi(questionPath,function (collection) {
          collection.chain().find({course_id:formdata.id}).remove();

          ExamModel.findAndUpdate({$loki:formdata.$loki},{
            exam_questions:questions
          });

          resolve(dispatch({
            type : 'question_items',
            info : questions
          }));

        });

      });

    });
  }

}

/**
 * 获取用户列表
 * @returns {function()}
 */
const getUserList = (formdata = {}) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      lokiApi(formdata.path,function (collection) {
        var doc = collection.find();
        if(doc){
          resolve(dispatch({
            type : 'user_list',
            info : doc
          }));
        }
      });
    });
  }
}


/**
 * 上传题库,处理Excel格式
 * @param formdata
 * @returns {function()}
 */
const postQuestionUpload = (formdata) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){

      ExamModel.findOne({$loki:parseInt(formdata.$loki)},(err,doc)=>{
        var questions = [], no = 0, data = {};
        var filename = formdata.filePath.split(/(\\|\/)/g).pop().replace('.xlsx','');
        if(doc.exam_questions && doc.exam_questions.length > 0){
          questions = doc.exam_questions;
          no = doc.exam_questions_index;
        };
        var id = 'q_'+no;
        data = {
          id : id,
          name : filename
        };

        var tfng_list = [], single_list = [], multiple_list = [];
        const questionPath = 'dba/questions/question_'+formdata.$loki+'.json';
        const workbook = XLSX.readFile(formdata.filePath);
        const first_sheet_name = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[first_sheet_name];
        const jsonArray = XLSX.utils.sheet_to_json(worksheet);
        if(jsonArray[0]['题干'] && jsonArray[0]['题型']){
        }else{
          return reject('导入文件格式错误');
        }

        let obj = {}, types = {'单选':'single','多选':'multiple','判断':'tfng'};


        lokiApi(questionPath,function (collection) {

          jsonArray.forEach(item=>{
            obj = {
              'eq_title' : item['题干'],
              'eq_type' : types[item['题型']],
              'A' : item['A'],
              'B' : item['B'],
              'C' : item['C'],
              'D' : item['D'],
              'eq_answer' : item['正确答案'],
              'eq_analysis' : item['答案解析'],
              'course_id' : id
            };

            var res = collection.insert(obj);
            if(obj.eq_type == 'tfng'){
              tfng_list.push(res.$loki);
            }else if(obj.eq_type == 'single'){
              single_list.push(res.$loki);
            }else if(obj.eq_type == 'multiple'){
              multiple_list.push(res.$loki);
            };
          });

          data['tfng_list'] = tfng_list;
          data['single_list'] = single_list;
          data['multiple_list'] = multiple_list;

          questions.push(data);

          ExamModel.findAndUpdate({$loki:formdata.$loki},{
            exam_questions_index : no + 1,
            exam_questions:questions
          });

          resolve(dispatch({
            type : 'question_items',
            info : questions
          }));
        });

      });
    });

  }
}

/**
 * 上传题库,重新上传
 * @param formdata
 * @returns {function()}
 */
const postQuestionReUpload = (formdata) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){

      ExamModel.findOne({$loki:parseInt(formdata.$loki)},(err,doc)=>{
        var filename = formdata.filePath.split(/(\\|\/)/g).pop().replace('.xlsx','');
        var questions = doc.exam_questions, index;
        questions.forEach((item,key)=>{
          if(item.id == formdata.id){
            questions[key]['name'] = filename;
            index = key;
          }
        });

        var tfng_list = [], single_list = [], multiple_list = [];
        const questionPath = 'dba/questions/question_'+formdata.$loki+'.json';
        const workbook = XLSX.readFile(formdata.filePath);
        const first_sheet_name = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[first_sheet_name];
        const jsonArray = XLSX.utils.sheet_to_json(worksheet);
        if(jsonArray[0]['题干'] && jsonArray[0]['题型']){
        }else{
          return reject('导入文件格式错误');
        }

        let obj = {}, types = {'单选':'single','多选':'multiple','判断':'tfng'};

        lokiApi(questionPath,function (collection) {
          collection.chain().find({course_id:formdata.id}).remove();
          jsonArray.forEach(item=>{
            obj = {
              'eq_title' : item['题干'],
              'eq_type' : types[item['题型']],
              'A' : item['A'],
              'B' : item['B'],
              'C' : item['C'],
              'D' : item['D'],
              'eq_answer' : item['正确答案'],
              'eq_analysis' : item['答案解析'],
              'course_id' : id
            };

            var res = collection.insert(obj);
            if(obj.eq_type == 'tfng'){
              tfng_list.push(res.$loki);
            }else if(obj.eq_type == 'single'){
              single_list.push(res.$loki);
            }else if(obj.eq_type == 'multiple'){
              multiple_list.push(res.$loki);
            };
          });

          data['tfng_list'] = tfng_list;
          data['single_list'] = single_list;
          data['multiple_list'] = multiple_list;

          questions.push(data);

          ExamModel.findAndUpdate({$loki:formdata.$loki},{
            exam_questions_index : no + 1,
            exam_questions:questions
          });

          resolve(dispatch({
            type : 'question_items',
            info : questions
          }));
        });

      });
    });

  }
}

/**
 * 上传用户,处理excel格式
 * @param formdata
 * @returns {function()}
 */
const postUserUpload = (formdata) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){

      var user_list = [];

      const workbook = XLSX.readFile(formdata.filePath);
      const first_sheet_name = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[first_sheet_name];
      const jsonArray = XLSX.utils.sheet_to_json(worksheet);

      const userPath = 'dba/users/user_'+formdata.$loki+'.json';
      lokiApi(userPath,function (collection) {

        collection.clear();
        jsonArray.forEach(function (value) {
          var res = collection.insert(value);
          user_list.push(res);
        });

        resolve(dispatch({
          type : 'user_list',
          userPath : userPath,
          info : user_list
        }));

        countUser({
          $loki : formdata.$loki,
          length : user_list.length
        });

      });

    });

  }
}

/**
 * 生成考试
 * @param formdata
 * @returns {function()}
 */
const postExamFinish = (formdata) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){

      RoomModel.find({
        exam_id : parseInt(formdata.$loki)
      },(err,doc)=>{
        if(!err){
          console.log(doc);
          if(doc){ doc.reverse() }
          let num = parseInt(doc[0]['room_number']), index = 0;
          const userPath = 'dba/users/user_'+formdata.$loki+'.json';
          lokiApi(userPath,function (collection,db) {

            const userlist = collection.find({});
            // collection.clear();
            userlist.forEach((value,key) => {
              let options = {room_id:null,room_name:null};
              if(key >= num){
                index ++;
                num += parseInt(doc[index]['room_number'])
              };
              options.room_id = doc[index].$loki;
              options.room_name = doc[index].room_name;
              options.room_time = doc[index].room_date + ' '+ doc[index].room_start_time + '~' + doc[index].room_end_time;
              collection.findAndUpdate(function (obj) {
                return obj.$loki == value.$loki;
              },function (obj) {
                var res = Object.assign(obj,options);
                return res;
              });

            });
            db.saveDatabase();


            ExamModel.findAndUpdate({$loki:formdata.$loki},{status:'finish'},(err,doc)=>{
              resolve(dispatch({
                type : 'exam_finish',
                $loki : formdata.$loki
              }))
            });

          });

        }else{
          reject('系统错误');
        }
      });

    });

  }
}

export default {
  getExamList,
  getExamDetail,
  postAddExam,
  postEditExam,
  postDeleteExam,
  getRoomList,
  postAddRoom,
  postEditRoom,
  postDeleteRoom,
  getQuestionList,
  postQuestionUpload,
  getUserList,
  postUserUpload,
  postExamFinish,
  changeQuestionNumber,
  deleteQuestion,
  postQuestionReUpload
}